package com.carleasoft.mps.adu.business.user.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.adu.business.basicsInfo.bean.entity.AuthorityUserBasicInfo;
import com.carleasoft.mps.adu.business.basicsInfo.bean.vo.AuthorityUserInfoVo;
import com.carleasoft.mps.adu.business.basicsInfo.dao.AuthorityUserBasicInfoMapper;
import com.carleasoft.mps.adu.business.basicsInfo.excel.ConvertTemplatePath;
import com.carleasoft.mps.adu.business.basicsInfo.excel.ExcelUtils;
import com.carleasoft.mps.adu.business.dept.bean.vo.DeptDetailVo;
import com.carleasoft.mps.adu.business.dept.dao.DeptDao;
import com.carleasoft.mps.adu.business.user.bean.entity.AuthorityUserEntity;
import com.carleasoft.mps.adu.business.user.bean.entity.MAuthorityStaggerHolidays;
import com.carleasoft.mps.adu.business.user.bean.po.MAuthorityStaggerHolidaysPo;
import com.carleasoft.mps.adu.business.user.bean.vo.*;
import com.carleasoft.mps.adu.business.user.dao.MAuthorityStaggerHolidaysMapper;
import com.carleasoft.mps.adu.common.constants.BusinessErrorEnum;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.Constants;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.utils.DateUtil;
import com.carleasoft.mps.core.utils.ExceptionUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.carleasoft.mps.adu.business.user.service.IMAuthorityStaggerHolidaysService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 人员轮休Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-12
 */
@Service
public class MAuthorityStaggerHolidaysServiceImpl extends ServiceImpl<MAuthorityStaggerHolidaysMapper, MAuthorityStaggerHolidays> implements IMAuthorityStaggerHolidaysService
{
    @Autowired
    private MAuthorityStaggerHolidaysMapper mAuthorityStaggerHolidaysMapper;

    @Autowired
    private AuthorityUserBasicInfoMapper authorityUserBasicInfoMapper;

    @Autowired
    private DeptDao deptDao;
    /**
     * 查询人员轮休
     * 
     * @param id 人员轮休主键
     * @return 人员轮休
     */
    @Override
    public MAuthorityStaggerHolidaysVo selectMAuthorityStaggerHolidaysById(Integer id)
    {
        return mAuthorityStaggerHolidaysMapper.selectMAuthorityStaggerHolidaysById(id);
    }

    /**
     * 查询人员轮休列表
     * 
     * @param mAuthorityStaggerHolidaysPo 人员轮休
     * @return 人员轮休
     */
    @Override
    public Page<MAuthorityStaggerHolidaysVo> selectMAuthorityStaggerHolidaysList(Page page, MAuthorityStaggerHolidaysPo mAuthorityStaggerHolidaysPo)
    {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        page.setCountId("selectPageCount");
        if (user.getUserCat() == Constants.ORDINARY_USER) {
            if(StringUtils.isEmpty(user.getDeptCode()) ||
                    (StringUtils.isNotEmpty(mAuthorityStaggerHolidaysPo.getDeptCode()) && !mAuthorityStaggerHolidaysPo.getDeptCode().equals(user.getDeptCode()))){
                return new Page<>();
            }
            mAuthorityStaggerHolidaysPo.setDeptCode(user.getDeptCode());
        }
        return mAuthorityStaggerHolidaysMapper.selectMAuthorityStaggerHolidaysList(page , mAuthorityStaggerHolidaysPo);
    }

    /**
     * 新增人员轮休
     * 
     * @param mAuthorityStaggerHolidays 人员轮休
     * @return 结果
     */
    @Override
    public boolean insertMAuthorityStaggerHolidays(MAuthorityStaggerHolidays mAuthorityStaggerHolidays)
    {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        AuthorityUserBasicInfo authorityUserBasicInfo = authorityUserBasicInfoMapper.selectOne(Wrappers.<AuthorityUserBasicInfo>lambdaQuery()
                .eq(AuthorityUserBasicInfo::getUserCode, user.getUserCode()));
        if(authorityUserBasicInfo.getUserSubmitFlag() == 0){
            throw ExceptionUtil.create(BusinessErrorEnum.COUNT_NO_JURISDICTION);
        }
        mAuthorityStaggerHolidays.setCreatePersonCode(user.getUserCode());
        mAuthorityStaggerHolidays.setCreatePersonName(user.getUserName());
        mAuthorityStaggerHolidays.setCreateTime(LocalDateTime.now());
        return this.save(mAuthorityStaggerHolidays);
    }

    /**
     * 根据部门Code分钟求和总条数
     * @return
     */
    @Override
    public List<MAuthorityDeptCountVo> selectMAuthorityDeptCountByDeptCode() {
        return mAuthorityStaggerHolidaysMapper.selectMAuthorityDeptCountByDeptCode(DateUtil.getDate());
    }

    /**
     * 修改人员轮休
     * 
     * @param mAuthorityStaggerHolidays 人员轮休
     * @return 结果
     */
    @Override
    public boolean updateMAuthorityStaggerHolidays(MAuthorityStaggerHolidays mAuthorityStaggerHolidays)
    {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        mAuthorityStaggerHolidays.setUpdatePersonCode(user.getUserCode());
        mAuthorityStaggerHolidays.setUpdatePersonName(user.getUserName());
        mAuthorityStaggerHolidays.setUpdateTime(LocalDateTime.now());
        return this.updateById(mAuthorityStaggerHolidays);
    }

    /**
     * 删除人员轮休信息
     * 
     * @param id 人员轮休主键
     * @return 结果
     */
    @Override
    public boolean deleteMAuthorityStaggerHolidaysById(Integer id)
    {
        return this.removeById(id);
    }

    /**
     * 导入人员轮休信息
     * @param file
     * @return
     */
    @Override
    public boolean userStaggerHolidaysExcel(MultipartFile file) {
        boolean isOk = false;
        List<MAuthorityStaggerHolidaysExcelVo> list = null;
        try {
            list = ExcelUtils.importExcel(file, MAuthorityStaggerHolidaysExcelVo.class);
            list = list.stream().filter(i -> i.getUserName() != null).collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (CollUtil.isNotEmpty(list)){
            Set<String> userNames = list.stream().map(MAuthorityStaggerHolidaysExcelVo::getUserName).collect(Collectors.toSet());
            List<AuthorityUserInfoVo> userInfoVos = authorityUserBasicInfoMapper.getUserInfoByUserNames(userNames);
            Map<String, AuthorityUserInfoVo> userMap = userInfoVos.stream().collect(Collectors.toMap(AuthorityUserInfoVo::getUserName, Function.identity()));
            //单位信息
            Set<String> deptNames = list.stream().map(MAuthorityStaggerHolidaysExcelVo::getDeptName).collect(Collectors.toSet());
            List<DeptDetailVo> deptInfoVos = deptDao.getDeptInfoByDeptNames(deptNames);
            Map<String, DeptDetailVo> deptMap = deptInfoVos.stream().collect(Collectors.toMap(DeptDetailVo::getDeptName, Function.identity()));
            for (MAuthorityStaggerHolidaysExcelVo staggerHolidaysExcelVo : list) {
                DeptDetailVo deptDetailVo = deptMap.get(staggerHolidaysExcelVo.getDeptName());
                AuthorityUserInfoVo userInfoVo = userMap.get(staggerHolidaysExcelVo.getUserName());
                MAuthorityStaggerHolidays staggerHolidays = new MAuthorityStaggerHolidays();
                staggerHolidays.setDeptCode(deptDetailVo.getDeptCode());
                staggerHolidays.setUserCode(userInfoVo.getUserCode());
                staggerHolidays.setLunXiouStartTime(staggerHolidaysExcelVo.getLunXiouStartTime());
                staggerHolidays.setLunXiouEndTime(staggerHolidaysExcelVo.getLunXiouEndTime());
                staggerHolidays.setLeaveAddress(staggerHolidaysExcelVo.getLeaveAddress());
                staggerHolidays.setMate(staggerHolidaysExcelVo.getMate());
                staggerHolidays.setParent(staggerHolidaysExcelVo.getParent());
                staggerHolidays.setParentLaw(staggerHolidaysExcelVo.getParentLaw());
                staggerHolidays.setReignRation(staggerHolidaysExcelVo.getReignRation());
                staggerHolidays.setReignNum(staggerHolidaysExcelVo.getReignNum());
                staggerHolidays.setLunXiouNumMonth(staggerHolidaysExcelVo.getLunXiouNumMonth());
                staggerHolidays.setRemark(staggerHolidaysExcelVo.getRemark());
                isOk = this.insertMAuthorityStaggerHolidays(staggerHolidays);
            }
        }
        return isOk;
    }

    /**
     * 导出人员轮休信息
     * @param startTime
     * @param response
     * @return
     */
    @Override
    public boolean export(HttpServletResponse response,String startTime) throws ParseException{
        MAuthorityStaggerHolidaysPo mAuthorityStaggerHolidaysPo = new MAuthorityStaggerHolidaysPo();
        Page<MAuthorityStaggerHolidaysVo> mAuthorityStaggerHolidaysVoPage = new Page<>();
        mAuthorityStaggerHolidaysPo.setSize(9999);
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        Date date = ft.parse(startTime);
        String year = DateUtil.getTimeStr(date, "yyyy");
        String month = DateUtil.getTimeStr(date, "MM");
        String day = DateUtil.getTimeStr(date, "dd");
        int week = 0;
        if(Integer.valueOf(day) < 8){
            week = 1;
        }else if(Integer.valueOf(day) >= 8 && Integer.valueOf(day) < 15){
            week = 2;
        }else if(Integer.valueOf(day) >= 15 && Integer.valueOf(day) < 22){
            week = 3;
        }else if(Integer.valueOf(day) >= 22 && Integer.valueOf(day) < 29){
            week = 4;
        }else if(Integer.valueOf(day) >= 29 && Integer.valueOf(day) < 31){
            week = 5;
        }
        mAuthorityStaggerHolidaysPo.setCreateTimeStart(date);
        String after = DateUtil.getSpecifiedDayAfter(startTime, 6);
        Date afterDate = ft.parse(after);
        Calendar rCalendar = Calendar.getInstance();
        rCalendar.setTime(afterDate);
        rCalendar.add(Calendar.HOUR,23);
        rCalendar.add(Calendar.MINUTE,59);
        rCalendar.add(Calendar.SECOND,59);
        mAuthorityStaggerHolidaysPo.setCreateTimeEnd(rCalendar.getTime());
        mAuthorityStaggerHolidaysVoPage = this.selectMAuthorityStaggerHolidaysList(new Page(mAuthorityStaggerHolidaysPo.getCurrent(), mAuthorityStaggerHolidaysPo.getSize()),mAuthorityStaggerHolidaysPo);

        if (CollUtil.isEmpty(mAuthorityStaggerHolidaysVoPage.getRecords())) {
            throw new BusinessException("1008611", "没有数据不允许导出");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ImportStaggerHolidaysExcelVo> importStaggerHolidaysExcelVoList = new ArrayList<>();
        int index = 1;
        for (MAuthorityStaggerHolidaysVo vo : mAuthorityStaggerHolidaysVoPage.getRecords()){
            ImportStaggerHolidaysExcelVo importStaggerHolidaysExcelVo = new ImportStaggerHolidaysExcelVo();
            BeanUtils.copyProperties(vo,importStaggerHolidaysExcelVo);
            importStaggerHolidaysExcelVo.setLunXiouStartTime(simpleDateFormat.format(vo.getLunXiouStartTime()));
            importStaggerHolidaysExcelVo.setLunXiouEndTime(simpleDateFormat.format(vo.getLunXiouEndTime()));
            importStaggerHolidaysExcelVo.setIndex(index);
            importStaggerHolidaysExcelVoList.add(importStaggerHolidaysExcelVo);
            index++;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", importStaggerHolidaysExcelVoList);
        map.put("month",month);
        map.put("week",week);
        String path = "\\template\\staggerHolidaysExport.xls";
        String fileName = month + "月" + ",第"+week+"周人员轮休数据";
        TemplateExportParams templatePath = new TemplateExportParams(ConvertTemplatePath.convertTemplatePath(path));
        try {
            ExcelUtils.exportExcel(templatePath, map, fileName, response);
        } catch (IOException e) {
        }

        return false;
    }
}
